import React, { useState, useEffect } from 'react'
import { Card, Button, Space, Modal, message, Tabs, Descriptions, Tag, Row, Col, Progress, Select } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, FileTextOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import DataTable from '../../../components/common/DataTable'
import Form from '../../../components/common/Form'

// 引入API
import { getExams, createExam, getExam, updateExam, deleteExam } from '../../../api/exam'

const { confirm } = Modal

const Exam = () => {
    const [loading, setLoading] = useState(false)
    const [dataSource, setDataSource] = useState([])
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    })
    const [visible, setVisible] = useState(false)
    const [currentExam, setCurrentExam] = useState(null)
    const [viewVisible, setViewVisible] = useState(false)
    const [viewExam, setViewExam] = useState(null)
    const [searchKeyword, setSearchKeyword] = useState('')

    // 使用真实API数据，移除模拟数据

    useEffect(() => {
        fetchExams()
    }, [pagination.current, pagination.pageSize, searchKeyword])

    // 获取考试数据
    const fetchExams = async () => {
        setLoading(true)
        try {
            const params = {
                page: pagination.current,
                pageSize: pagination.pageSize,
                keyword: searchKeyword
            }
            const response = await getExams(params)
            setDataSource(response.data || [])
            setPagination({
                ...pagination,
                total: response.total || 0
            })
        } catch (error) {
            console.error('获取考试列表失败:', error)
            message.error('获取考试列表失败')
        } finally {
            setLoading(false)
        }
    }

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination)
    }

    // 处理搜索
    const handleSearch = (value) => {
        setSearchKeyword(value)
    }

    // 添加考试
    const handleAdd = () => {
        setCurrentExam(null)
        setVisible(true)
    }

    // 编辑考试
    const handleEdit = async (record) => {
        try {
            setLoading(true)
            // 获取最新的考试详情
            const response = await getExam(record.id)
            setCurrentExam(response.data)
            setVisible(true)
        } catch (error) {
            console.error('获取考试详情失败:', error)
            message.error('获取考试详情失败')
        } finally {
            setLoading(false)
        }
    }

    // 查看考试详情
    const handleView = async (record) => {
        try {
            setLoading(true)
            // 获取最新的考试详情
            const response = await getExam(record.id)
            setViewExam(response.data)
            setViewVisible(true)
        } catch (error) {
            console.error('获取考试详情失败:', error)
            message.error('获取考试详情失败')
        } finally {
            setLoading(false)
        }
    }

    // 删除考试
    const handleDelete = (id) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除这个考试吗？此操作不可恢复。',
            onOk: async () => {
                try {
                    setLoading(true)
                    await deleteExam(id)
                    message.success('删除成功')
                    // 重新获取列表数据
                    fetchExams()
                } catch (error) {
                    console.error('删除考试失败:', error)
                    message.error('删除考试失败')
                } finally {
                    setLoading(false)
                }
            }
        })
    }

    // 表单提交
    const handleFormSubmit = async (values) => {
        try {
            setLoading(true)
            if (currentExam) {
                // 编辑考试
                await updateExam(currentExam.id, values)
                message.success('编辑成功')
            } else {
                // 添加考试
                await createExam(values)
                message.success('添加成功')
            }
            // 关闭模态框
            setVisible(false)
            // 重新获取列表数据
            fetchExams()
        } catch (error) {
            console.error('保存考试失败:', error)
            message.error(error.response?.data?.message || '保存考试失败')
        } finally {
            setLoading(false)
        }
    }

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80
        },
        {
            title: '考试名称',
            dataIndex: 'title',
            key: 'title',
            render: (text, record) => (
                <a onClick={() => handleView(record)}>{text}</a>
            )
        },
        {
            title: '所属部门',
            dataIndex: 'department',
            key: 'department'
        },
        {
            title: '开始时间',
            dataIndex: 'startTime',
            key: 'startTime'
        },
        {
            title: '结束时间',
            dataIndex: 'endTime',
            key: 'endTime'
        },
        {
            title: '时长(分钟)',
            dataIndex: 'duration',
            key: 'duration'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (text) => {
                let color = 'blue'
                if (text === '已结束') color = 'green'
                if (text === '未开始') color = 'orange'
                if (text === '进行中') color = 'blue'
                return <Tag color={color}>{text}</Tag>
            }
        },
        {
            title: '参与人数',
            dataIndex: 'participantCount',
            key: 'participantCount'
        },
        {
            title: '操作',
            key: 'action',
            width: 180,
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="text" 
                        icon={<EditOutlined />} 
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button 
                        type="text" 
                        danger 
                        icon={<DeleteOutlined />} 
                        onClick={() => handleDelete(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ]

    return (
        <div className="exam-container">
            <Card title="考试管理" extra={
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                    添加考试
                </Button>
            }>
                <DataTable 
                    columns={columns}
                    dataSource={dataSource}
                    loading={loading}
                    rowKey="id"
                    pagination={pagination}
                    onChange={handleTableChange}
                    onSearch={handleSearch}
                    onRefresh={fetchExams}
                    searchPlaceholder="搜索考试名称/部门"
                />
            </Card>

            {/* 考试表单模态框 */}
            <Modal
                title={currentExam ? '编辑考试' : '添加考试'}
                open={visible}
                onCancel={() => setVisible(false)}
                footer={null}
                width={700}
            >
                <Form
                    initialValues={currentExam}
                    onFinish={handleFormSubmit}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name="title"
                        label="考试名称"
                        rules={[{ required: true, message: '请输入考试名称' }]}
                    >
                        <input placeholder="请输入考试名称" />
                    </Form.Item>
                    <Form.Item
                        name="description"
                        label="考试描述"
                        rules={[{ required: true, message: '请输入考试描述' }]}
                    >
                        <textarea placeholder="请输入考试描述" rows={4} />
                    </Form.Item>
                    <Form.Item
                        name="department"
                        label="所属部门"
                        rules={[{ required: true, message: '请选择所属部门' }]}
                    >
                        <select>
                            <option value="人事部">人事部</option>
                            <option value="技术部">技术部</option>
                            <option value="市场部">市场部</option>
                            <option value="财务部">财务部</option>
                            <option value="管理部">管理部</option>
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="startTime"
                        label="开始时间"
                        rules={[{ required: true, message: '请选择开始时间' }]}
                    >
                        <input type="datetime-local" />
                    </Form.Item>
                    <Form.Item
                        name="endTime"
                        label="结束时间"
                        rules={[{ required: true, message: '请选择结束时间' }]}
                    >
                        <input type="datetime-local" />
                    </Form.Item>
                    <Form.Item
                        name="duration"
                        label="考试时长"
                        rules={[{ required: true, message: '请输入考试时长' }]}
                    >
                        <input type="number" placeholder="请输入考试时长(分钟)" />
                    </Form.Item>
                    <Form.Item
                        name="totalScore"
                        label="总分值"
                        rules={[{ required: true, message: '请输入总分值' }]}
                    >
                        <input type="number" placeholder="请输入总分值" />
                    </Form.Item>
                    <Form.Item
                        name="passingScore"
                        label="及格分数"
                        rules={[{ required: true, message: '请输入及格分数' }]}
                    >
                        <input type="number" placeholder="请输入及格分数" />
                    </Form.Item>
                    <Form.Item
                        name="status"
                        label="状态"
                        rules={[{ required: true, message: '请选择状态' }]}
                    >
                        <select>
                            <option value="未开始">未开始</option>
                            <option value="进行中">进行中</option>
                            <option value="已结束">已结束</option>
                            <option value="已取消">已取消</option>
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="questionCount"
                        label="题目数量"
                        rules={[{ required: true, message: '请输入题目数量' }]}
                    >
                        <input type="number" placeholder="请输入题目数量" />
                    </Form.Item>
                    <Form.Item
                        name="participantCount"
                        label="参与人数"
                        rules={[{ required: true, message: '请输入参与人数' }]}
                    >
                        <input type="number" placeholder="请输入参与人数" />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 考试详情模态框 */}
            <Modal
                title="考试详情"
                open={viewVisible}
                onCancel={() => setViewVisible(false)}
                footer={null}
                width={700}
            >
                {viewExam && (
                    <div className="exam-detail">
                        <Row gutter={[16, 16]}>
                            <Col span={24}>
                                <Tabs defaultActiveKey="1">
                                    <Tabs.TabPane tab="基本信息" key="1">
                                        <Descriptions bordered column={2}>
                                            <Descriptions.Item label="ID">{viewExam.id}</Descriptions.Item>
                                            <Descriptions.Item label="考试名称">{viewExam.title}</Descriptions.Item>
                                            <Descriptions.Item label="所属部门">{viewExam.department}</Descriptions.Item>
                                            <Descriptions.Item label="开始时间">{viewExam.startTime}</Descriptions.Item>
                                            <Descriptions.Item label="结束时间">{viewExam.endTime}</Descriptions.Item>
                                            <Descriptions.Item label="考试时长">{viewExam.duration}分钟</Descriptions.Item>
                                            <Descriptions.Item label="总分值">{viewExam.totalScore}</Descriptions.Item>
                                            <Descriptions.Item label="及格分数">{viewExam.passingScore}</Descriptions.Item>
                                            <Descriptions.Item label="题目数量">{viewExam.questionCount}</Descriptions.Item>
                                            <Descriptions.Item label="参与人数">{viewExam.participantCount}</Descriptions.Item>
                                            <Descriptions.Item label="状态">
                                                <Tag color={viewExam.status === '已结束' ? 'green' : (viewExam.status === '未开始' ? 'orange' : 'blue')}>
                                                    {viewExam.status}
                                                </Tag>
                                            </Descriptions.Item>
                                            <Descriptions.Item label="描述" span={2}>{viewExam.description}</Descriptions.Item>
                                        </Descriptions>
                                    </Tabs.TabPane>
                                    <Tabs.TabPane tab="题目列表" key="2">
                                        <p>此功能尚未实现，将显示此考试的题目列表。</p>
                                    </Tabs.TabPane>
                                    <Tabs.TabPane tab="参与人员" key="3">
                                        <p>此功能尚未实现，将显示参与此考试的员工列表。</p>
                                    </Tabs.TabPane>
                                </Tabs>
                            </Col>
                        </Row>
                    </div>
                )}
            </Modal>
        </div>
    )
}

export default Exam